//
//  QTAFNnetWorkTool.m
//  MyCar
//
//  Created by dlios on 15-9-1.
//  Copyright (c) 2015年 lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "QTAFNnetWorkTool.h"
#import "MBProgressHUD.h"
#import "AFNetworking.h"
#import <CommonCrypto/CommonDigest.h>
//-fno-obje-arc arc下用mrc
//-fobjc-arc mrc下用arc
@implementation QTAFNnetWorkTool
+ (void)getUrl:(NSString *)url
          body:(id)body
  hudSuperView:(id)hudSuperView
        result:(QTResult)result
    headerFile:(NSDictionary *)headerFile
       success:(void(^)(id result))success
       //failure:(void(^)(NSError *error))failure
{
    //加载视图
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:hudSuperView animated:YES];
    hud.labelText = @"正在加载···";
    
    //1.获取网络请求管理类
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    
    //2.为网络请求加请求头
    if (headerFile) {
        for (NSString *key in headerFile.allKeys) {
            [manager.requestSerializer setValue:headerFile[key] forHTTPHeaderField:key];
        }
    }
    
    //3.设置返回值类型
    switch (result) {
        case QTData:
            manager.responseSerializer = [AFHTTPResponseSerializer serializer];
            break;
        case QTXML:
            manager.responseSerializer = [AFXMLParserResponseSerializer serializer];
            break;
        case QTJSON:
            manager.responseSerializer = [AFJSONResponseSerializer serializer];
            break;
        default:
            break;
    }
    
    //4.设置网络请求返回值所支持的参数类型
    [manager.responseSerializer setAcceptableContentTypes:[NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/css",@"text/plain",@"application/javascript", nil]];
    
    //获取沙盒路径
    NSFileManager *fileManger = [NSFileManager defaultManager];
    NSArray *sandBox = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    //创建文件夹(有就不会创建)
    NSString *filePath = [sandBox[0] stringByAppendingPathComponent:@"travelWorld"];
    [fileManger createDirectoryAtPath:filePath withIntermediateDirectories:YES attributes:nil error:nil];
    
    //NSString *str = [NSString stringWithFormat:@"%ld.plist",[url hash]];//截取文件名
    //NSString *str = [url stringByReplacingOccurrencesOfString:@"/" withString:@""];//截取文件名
    NSString *str = [NSString stringWithFormat:@"%@.plist",[self md5:url]];
//    NSLog(@"%@",NSHomeDirectory());
    
    
    NSString *caches = [filePath stringByAppendingPathComponent:str];

    //5.获取数据
    //5.1 发送网络请求
    [manager GET:url parameters:body success:^(AFHTTPRequestOperation *operation, id responseObject){
        if (responseObject) {
    
            hud.hidden = YES;
            success(responseObject);//成功回调
            NSLog(@"有网络--网络取数据");
            //把数据缓存到本地
            [NSKeyedArchiver archiveRootObject:responseObject toFile:caches];
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        if (error) {
            
            //5.2 从本地反归档取数据
            id responseObject = [NSKeyedUnarchiver unarchiveObjectWithFile:caches];
            
            if (responseObject != nil) {
                NSLog(@"无网络--本地取数据");
                success(responseObject);
            }
            hud.hidden = YES;
            NSLog(@"%@",error);//失败打印
        }
    }];
}
// MD5是一种不可逆的加密算法，只能用作一些检验过程，不能恢复其原文。apple还提供了RSA、DES、AES等加密算法
+ (NSString *)md5:(NSString *)str {
    const char *cStr = [str UTF8String]; // 转换成utf-8
    unsigned char result[16]; // 开辟一个16字节（128位：md5加密出来就是128位/bit）的空间（一个字节=8字位=8个二进制数）
    CC_MD5( cStr, strlen(cStr), result);
    /*
     extern unsigned char *CC_MD5(const void *data, CC_LONG len, unsigned char *md)官方封装好的加密方法
     把cStr字符串转换成了32位的16进制数列（这个过程不可逆转） 存储到了result这个空间中
     */
    return [NSString stringWithFormat:
            @"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
            result[0], result[1], result[2], result[3],
            result[4], result[5], result[6], result[7],
            result[8], result[9], result[10], result[11],
            result[12], result[13], result[14], result[15]
            ];
    /*
     x表示十六进制，%02X  意思是不足两位将用0补齐，如果多余两位则不影响
     NSLog("%02X", 0x888);  //888
     NSLog("%02X", 0x4); //04
     */
}

////判断网络状态------------------
//+ (void)networkReachability{
//    AFNetworkReachabilityManager *checkNetwork = [AFNetworkReachabilityManager sharedManager];
//    // 开始网络检测
//    [checkNetwork startMonitoring];
//    
//    [checkNetwork setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
//        if (status == AFNetworkReachabilityStatusNotReachable){
//            [QTSingleton shareSingleton].isWIFI = NO;
//        }else{
//            [QTSingleton shareSingleton].isWIFI = YES;
//        }
//    }];
//    // 停止网络检测
//    [checkNetwork stopMonitoring];
//}
+ (void)postUrl:(NSString *)url
           body:(id)body
   hudSuperView:(id)hudSuperView
         result:(QTResult)result
   requestStyle:(QTRequestStyle)requestStyle
     headerFile:(NSDictionary *)headerFile
        success:(void(^)(id result))success
        failure:(void(^)(NSError *error))failure
{
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:hudSuperView animated:YES];
    hud.labelText = @"正在加载";
    //1.获取网络请求管理类
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    //2.网络请求请求体Body的类型
    switch (requestStyle) {
        case QTRequestJSON:
            manager.requestSerializer = [AFJSONRequestSerializer serializer];
            break;
        case QTRequestString://按原顺序返回字典数据
            [manager.requestSerializer setQueryStringSerializationWithBlock:^NSString *(NSURLRequest *request, id parameters, NSError *__autoreleasing *error) {
                return parameters;
            }];
            break;
        default:
            break;
    }
    //3.为网络请求加请求头
    if (headerFile) {
        for (NSString *key in headerFile.allKeys) {
            [manager.requestSerializer setValue:headerFile[key] forHTTPHeaderField:key];
        }
    }
    //4.网络请求返回值的数据类型
    switch (result) {
        case QTData:
            manager.responseSerializer = [AFHTTPResponseSerializer serializer];
            break;
        case QTXML:
            manager.responseSerializer = [AFXMLParserResponseSerializer serializer];
            break;
        case QTJSON:
            manager.responseSerializer = [AFJSONResponseSerializer serializer];
            break;
        default:
            break;
    }
    //5.设置网络请求返回值支持的类型
    [manager.responseSerializer setAcceptableContentTypes:[NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/css",@"text/plain", nil]];
    //6.发送网络请求
    [manager POST:url parameters:body success:^(AFHTTPRequestOperation *operation, id responseObject) {
        if (responseObject) {
            success(responseObject);
            hud.hidden = YES;
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        if (error) {
            failure(error);
            hud.hidden = YES;
        }
    }];
}
@end
